﻿using System.Text;
using Castle.DynamicProxy;
using Dexter.Logger.Contracts;

namespace Dexter.Dependency.Castle.Interceptors {

	///<summary>
	///	Log Every init and end methods call.
	///</summary>
	public class LoggingInterceptor : IInterceptor {
		readonly IDexterContainer container;

		/// <summary>
		/// Initializes a new instance of the <see cref="LoggingInterceptor"/> class.
		/// </summary>
		/// <param name="container">The container.</param>
		public LoggingInterceptor ( IDexterContainer container ) {
			this.container = container;
		}

		#region IInterceptor Members

		/// <summary>
		/// 	Intercepts the specified invocation.
		/// </summary>
		/// <param name = "invocation">The invocation.</param>
		public void Intercept ( IInvocation invocation ) {
			ILogger logger = container.Resolve<ILoggerFactory>().Create ( invocation.TargetType );

			StringBuilder sb = null;

			if ( logger.IsDebugEnabled ) {
				sb = new StringBuilder ( invocation.TargetType.FullName )
					.Append ( "." )
					.Append ( invocation.Method )
					.Append ( "(" );
				for ( int i = 0; i < invocation.Arguments.Length; i++ ) {
					if ( i > 0 ) {
						sb.Append ( ", " );
					}

					sb.Append ( invocation.Arguments[ i ] );
				}

				sb.Append ( ")" );
				logger.Debug ( sb.ToString ( ) );
			}

			invocation.Proceed ( );

			if ( logger.IsDebugEnabled ) {
				logger.DebugFormat ( "Result of {0} is: {1}" , sb , invocation.ReturnValue );
			}
		}

		#endregion
	}
}